<script setup>
import { ref,reactive, nextTick,onActivated,getCurrentInstance,onMounted, watch  } from 'vue'; 
import { useRoute,useRouter } from 'vue-router';
import { ElMessage,ElMessageBox  } from 'element-plus';
import { keepMaterials } from '@/api/ShopDatabase/materials.js';
import TopBar from '@/components/Topbar/index.vue';
import getRules from "@/validUtils";
import { closeTag } from '@/utils/globalWay'
import UploadImg from '@/components/UploadImg/index.vue';
import { getBaseSetting,getAllCommodityExtraAttributes } from '@/api/ShopDatabase/goodsSetting.js'
import { useDistInfoStore } from '@/stores/dict.js';
import { getFieldValue,generateInitials,limitFloat,limitInt,giveFloatMin,giveIntMin } from '@/utils/common.js'
const route = useRoute();
const router = useRouter();
const backValue = ref('MaterialsManagementIndex');
const tabName = ref("新增物资");
const moduleType = ref("基础信息");
const distInfoStore = useDistInfoStore();
const formRef = ref(null);
const batchFormRef = ref(null);
const rules = ref({
    businessBrandId:[
        { required:true,validator: (rule, value, callback) => {
                if (value.length<=0) {
                    return callback(new Error("请选择经营品牌"));
                }
                return callback();
            }, trigger: "change"
        },
    ],

})
const batchRules = ref({
    wholesaleInfoClassification:[
        { required:true,validator: (rule, value, callback) => {
                if (value.length<=0) {
                    return callback(new Error("请选择批发分类"));
                }
                return callback();
            } 
        },
    ],
    wholesaleInfoDetails:[
        { required:true,validator: (rule, value, callback) => {
                if (((value??'') === '') && (batchForm.value.wholesalepictureList.length<=0)) {
                    return callback(new Error("请输入物资详情"));
                }
                return callback();
            }, trigger: "change"
        },
    ],
})
const brandList = computed(()=>{
    return distInfoStore.getDistInfo("经营品牌").map(lis=>{
        return {
            value:lis.id,
            label:lis.permissionName
        }
    })
})
const form = ref({
    code:"",
    needValue:"1",
    categoryId:"",
    businessBrandId:[],
    goodsName:"",
    barcode:"",
    mnemonicCode:"",
    specification:"",
    unit:"",
    origin:"",
    manufacturer:"",
    carriedStandard:"",
    activityImg:[],
    latestPurchasePrice:"",

})
const batchForm = ref({
    wholesaleInfoState:1,
    wholesaleInfoPrice:"",
    wholesaleInfoClassification:[],
    wholesaleInfoMinimumPurchase:1,
    wholesaleInfoDetails:"",
    wholesalepictureList:[],
    needValue:"1"
})
const changeWholesaleInfoState = ()=>{
    batchForm.value.wholesaleInfoPrice = "";
    batchForm.value.wholesaleInfoClassification = [];
    batchForm.value.wholesaleInfoMinimumPurchase = "";
    batchForm.value.wholesaleInfoDetails = "";
    batchForm.value.wholesalepictureList = [];
}
const backValueActivityImg = (img)=>{
    form.value.activityImg = img;
    formRef.value.clearValidate(['activityImg']);
}
const backValueActivityDetailImg = (img)=>{
    batchForm.value.wholesalepictureList = img;
    batchFormRef.value.clearValidate(['wholesaleInfoDetails']);

}
const setMnemonicCode = (value)=>{
    form.value.mnemonicCode = generateInitials(value);
}
const useUsage = ref(
    [
        {
            usageTotalDose:"",
            usageUnit:"",
            usageWayOfUse:[],
            usageDosa:"",
            usageFrequency:"",
            usageDays:""
        },

    ]
);
const img1 = ref(new URL("@/assets/images/login-bg3.png",import.meta.url));
const classifyList = ref([]);
const unitList = ref([]);
const wayList = ref([]);
const frequencyList = ref([]);
const batchClassifyList = ref([]);
const _getBaseSetting = async ()=>{
    classifyList.value = [];
    unitList.value = [];
    wayList.value = [];
    frequencyList.value = [];
    batchClassifyList.value = [];
    try{
        let result = await getBaseSetting();
        classifyList.value =  getFieldValue('类别',result,'id');
        unitList.value = getFieldValue("单位",result);
        wayList.value = getFieldValue("使用途径",result);
        frequencyList.value = getFieldValue("使用频率",result);
        batchClassifyList.value = getFieldValue("批发分类",result);
    }catch(e){

    }
}

_getBaseSetting();
const goodsAttributesList = ref([]);
const _getAllCommodityExtraAttributes = async ()=>{
    goodsAttributesList.value = [];
    try{
        let result = await getAllCommodityExtraAttributes();
        if(result.goodsAttributesList && result.goodsAttributesList.length>0){
            goodsAttributesList.value = result.goodsAttributesList.filter(value=>value.disabled == 0).map(lis=>{
                if(lis.fieldType == 3 || lis.fieldType == 4){
                    lis.optionContent = lis.optionContent.split(",")
                }
                if(lis.fieldType == 4){
                    return {...lis,fieldValue:[]};
                }else{
                    return {...lis,fieldValue:""};
                }

            })
            console.log(goodsAttributesList.value,222);
        }

    }catch(e){
        console.log(e);
    }
}
_getAllCommodityExtraAttributes();
const keepLoading = ref(false);
const submit  = ()=>{
    formRef.value.validate((validOne, fields,msg)=>{
        console.log(validOne, fields,msg,222);
        if(validOne){
            batchFormRef.value.validate(async (validTwo, fields)=>{
                if(validTwo){
                    // if(form.value.activityImg.length<=0){
                    //     ElMessage.error('物资图片未传');
                    //     moduleType.value = '基础信息';
                    //     return;
                    // }

                    let params = {
                        add:1,
                        category:classifyList.value.find(item=>form.value.categoryId === item.value)?.label ?? '',
                        categoryId:form.value.categoryId,
                        businessBrandId:form.value.businessBrandId.join(','),
                        goodsName:form.value.goodsName,
                        barcode:form.value.barcode,
                        mnemonicCode:form.value.mnemonicCode,
                        specification:form.value.specification,
                        unit:form.value.unit,
                        origin:form.value.origin,
                        manufacturer:form.value.manufacturer,
                        carriedStandard:form.value.carriedStandard,
                        busiCommodityPictureVoList:[...form.value.activityImg.map(value=>{
                            return {
                                url:value,
                                sourceType:4    
                            }
                        }),...batchForm.value.wholesalepictureList.map(value=>{
                            return {
                                url:value,
                                sourceType:6    
                            }
                        })],
                        latestPurchasePrice:form.value.latestPurchasePrice,
                        extraAttributesBindVoList:[],
                        usageTotalDose:useUsage.value[0].usageTotalDose,
                        usageUnit:useUsage.value[0].usageUnit,
                        usageWayOfUse:useUsage.value[0].usageWayOfUse.join(','),
                        usageDosa:useUsage.value[0].usageDosa,
                        usageFrequency:useUsage.value[0].usageFrequency,
                        usageDays:useUsage.value[0].usageDays,
                        wholesaleInfoState:batchForm.value.wholesaleInfoState,
                        wholesaleInfoPrice:batchForm.value.wholesaleInfoPrice,
                        wholesaleInfoClassification:batchForm.value.wholesaleInfoClassification.join(','),
                        wholesaleInfoMinimumPurchase:batchForm.value.wholesaleInfoMinimumPurchase,
                        wholesaleInfoDetails:batchForm.value.wholesaleInfoDetails,
                    }
                    goodsAttributesList.value.forEach(lis=>{
                        params.extraAttributesBindVoList.push({
                            sourceType:4,
                            extraAttributesName:lis.fieldName,
                            optionContent:lis.fieldType == 3 || lis.fieldType ==4?lis.optionContent.join(','):"",
                            fieldType:lis.fieldType,
                            extraAttributesValue:lis.fieldType ==4?lis.fieldValue.join(','):lis.fieldValue,
                            extraAttributesId:lis.id
                        })
                    })
                    keepLoading.value = true;
                    try{
                        await keepMaterials(params)
                        ElMessage.success('新增成功');
                        closeTag(route.name);
                        router.replace({name:backValue.value});
                    }catch(e){
                    }finally{
                        keepLoading.value = false;
                    }
                 

                }else{
                    ElMessage.error('批发信息未填写完整');
                    moduleType.value = '批发信息';
                }
            });
        }else{
            ElMessage.error('基础信息未填写完整');
            moduleType.value = '基础信息';
        }
    });
}
const cancelInfo = ()=>{
    closeTag(route.name);
    router.replace({name:backValue.value});
}


</script>
<template>
    <div class="page-contain">
        <TopBar :backValue="backValue" :tabName="tabName">
            <template #operate>
                <el-button style="min-width: 68px" @click="cancelInfo">取消</el-button>
                <el-button type="primary" style="min-width: 68px" @click="submit" :loading="keepLoading">保存</el-button>
            </template>
        </TopBar>
        <div class="info-contain">
            <div class="btn-opea">
                <el-radio-group v-model="moduleType">
                    <el-radio-button label="基础信息" />
                    <el-radio-button label="批发信息" />
                </el-radio-group>
            </div>
            <div class="info-lis" v-show="moduleType == '基础信息'">

                <el-form :model="form" label-width="80px" :rules="rules" ref="formRef">
                    <div class="lis-head">
                        <div class="icon-view">
                            <div class="icon-view-on"></div>
                        </div>
                        <span class="label-name">基础属性</span>

                    </div>
                    <div class="lis-item">
                        <div class="lis-i">
                            <el-form-item label="物资编号"  required prop="needValue">
                                <el-input v-model="form.code" placeholder="保存后自动生成" disabled style="width:260px"/>
                            </el-form-item>
                        </div>
                        <div class="lis-i">
                            <el-form-item label="类别">
                                <el-select v-model="form.categoryId" placeholder="请选择"  clearable v-selectClose style="width:260px">
                                    <el-option :label="item.label" :value="item.value" v-for="(item,index) in classifyList" :key="index"/>
                                </el-select> 
                            </el-form-item>
                        </div>
                        <div class="lis-i">
                            <el-form-item label="经营品牌" prop="businessBrandId" >
                                <el-select v-model="form.businessBrandId" placeholder="请选择"  clearable v-selectClose style="width:260px" multiple collapse-tags>
                                    <el-option :label="item.label" :value="item.value" v-for="(item,index) in brandList" :key="index"/>
                                </el-select> 
                            </el-form-item>
                        </div>
                    </div>
                    <div class="lis-item">
                        <div class="lis-i">
                            <el-form-item label="物资名称" :rules="getRules('input', '物资名称')" prop="goodsName">
                                <el-input v-model="form.goodsName" placeholder="请输入 " @blur="setMnemonicCode(form.goodsName)" style="width:260px" :maxlength="50"/>   
                            </el-form-item>
                        </div>
                        <div class="lis-i">
                            <el-form-item label="条码"  prop="barcode">
                                <el-input v-model="form.barcode " placeholder="请输入 " style="width:260px" :maxlength="50"/>   
                            </el-form-item>
                        </div>  
                        <div class="lis-i">
                            <el-form-item label="助记码" :rules="getRules('input', '助记码')" prop="mnemonicCode">
                                <el-input v-model="form.mnemonicCode " placeholder="请输入 " style="width:260px"/>   
                            </el-form-item>
                        </div>

                    </div>
                    <div class="lis-item">
                        <div class="lis-i">
                            <el-form-item label="物资规格" >
                                <el-input v-model="form.specification" placeholder="请输入 " style="width:260px" :maxlength="50"/>   
                            </el-form-item>
                        </div>
                        <div class="lis-i">
                            <el-form-item label="单位" >
                                <el-select v-model="form.unit" placeholder="请选择"  clearable v-selectClose style="width:260px" filterable>
                                    <el-option :label="item.label" :value="item.value" v-for="(item,index) in unitList" :key="index"/>
                                </el-select>   
                            </el-form-item>
                        </div>  
                        <div class="lis-i">
                            <el-form-item label="产地">
                                <el-input v-model="form.origin " placeholder="请输入 " style="width:260px" :maxlength="50"/>   
                            </el-form-item>
                        </div>

                    </div>
                    <div class="lis-item">
                        <div class="lis-i">
                            <el-form-item label="生产厂家">
                                <el-input v-model="form.manufacturer" placeholder="请输入 " style="width:260px" :maxlength="50"/>   
                            </el-form-item>
                        </div>
                        <div class="lis-i">
                            <el-form-item label="执行标准">
                                <el-input v-model="form.carriedStandard " placeholder="请输入 " style="width:260px" :maxlength="50"/>   
                            </el-form-item>
                        </div>  


                    </div>
                    <div class="lis-item">
                        <div class="lis-i" style="width:100%">
                            <el-form-item label="物资图片">
                                <div style="width:100%;position: relative;">
                                    <UploadImg :multiple="true" @backValue="backValueActivityImg"  :imageListUrlInfo="form.activityImg">
                                    </UploadImg>
                                    <div style="font-size:12px;color:#666666;width:100%;">
                                        支持jpg、jpeg、png格式；图片比例1:1；建议为300*300；最多5张；单张不超过5M
                                    </div>
                                </div>

  
                            </el-form-item>
                        </div>
                    </div>

                    <div class="lis-item">
                        <div class="lis-i">
                            <el-form-item label="最新进价">
                                <el-input v-model="form.latestPurchasePrice" placeholder="请输入 " style="width:260px" @input="()=>{form.latestPurchasePrice=limitFloat(form.latestPurchasePrice)}" @blur="()=>{form.latestPurchasePrice=giveFloatMin(form.latestPurchasePrice)}"/>   
                            </el-form-item>
                        </div>
                    </div>
                    <div class="lis-item">
                        <div class="lis-i" style="width:100%">
                            <el-form-item label="用法用量">
                                <div style="width:100%;margin-top:8px" class="normal-table">
                                    <el-table :data="useUsage" style="width: 100%" stripe>
                                        <el-table-column prop="name" label="总剂量">
                                            <template #default="scoped">
                                                <el-input v-model="scoped.row.usageTotalDose" placeholder="请输入 " style="width:120px" size="small" :maxlength="50"/>   
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="date" label="单位">
           
                                            <template #default="scoped">
                                                <el-select v-model="scoped.row.usageUnit" placeholder="请选择"  clearable v-selectClose style="width:120px" size="small" filterable>
                                                    <el-option :label="item.label" :value="item.value" v-for="(item,index) in unitList" :key="index"/>

                                                </el-select>
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="name" label="使用途径">
                                            <template #default="scoped">
                                                <el-select v-model="scoped.row.usageWayOfUse" placeholder="请选择"  clearable v-selectClose style="width:120px" size="small" multiple collapse-tags>
                                                    <el-option :label="item.label" :value="item.value" v-for="(item,index) in wayList" :key="index"/>

                                                </el-select>
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="name" label="单次用量">
                                            <template #default="scoped">
                                                <el-input v-model="scoped.row.usageDosa" placeholder="请输入 " style="width:120px" size="small" @input="()=>{scoped.row.usageDosa=limitFloat(scoped.row.usageDosa)}" @blur="()=>{scoped.row.usageDosa=giveFloatMin(scoped.row.usageDosa)}"/>   
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="name" label="使用频率">
                                            <template #default="scoped">
                                                <el-select v-model="scoped.row.usageFrequency" placeholder="请选择"  clearable v-selectClose style="width:120px" size="small">
                                                    <el-option :label="item.label" :value="item.value" v-for="(item,index) in frequencyList" :key="index"/>
                                                </el-select>
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="name" label="使用天数">
                                            <template #default="scoped">
                                                <el-input v-model="scoped.row.usageDays" placeholder="请输入 " style="width:120px" size="small" @input="()=>{scoped.row.usageDays=limitInt(scoped.row.usageDays)}" @blur="()=>{scoped.row.usageDays=giveIntMin(scoped.row.usageDays)}"/>   
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                </div>
                            </el-form-item>
                        </div>
                    </div>
                    <div class="lis-head">
                        <div class="icon-view">
                            <div class="icon-view-on"></div>
                        </div>
                        <span class="label-name">自定义属性</span>

                    </div>
                    <div class="lis-item">
                        <div class="lis-i lis-i-other" v-for="(item,index) in goodsAttributesList" :key="index">
                            <div class="l-name">{{ item.fieldName }}</div>
                            <div v-if="item.fieldType == 1">
                                <el-input v-model="item.fieldValue" placeholder="请输入" style="width:260px" :maxlength="100"/>
                            </div>
                            <div v-if="item.fieldType == 2">
                                <el-input v-model="item.fieldValue" placeholder="请输入" style="width:260px"  @input="()=>{item.fieldValue=limitFloat(item.fieldValue)}" @blur="()=>{item.fieldValue=giveFloatMin(item.fieldValue)}"/>
                            </div>
                            <div v-if="item.fieldType == 3">
                                <el-select v-model="item.fieldValue" placeholder="请选择"  clearable v-selectClose style="width:260px">
                                    <el-option :label="lis" :value="lis" v-for="(lis,key) in item.optionContent" :key="key"/>
                                </el-select>  
                            </div>
                            <div v-if="item.fieldType == 4">
                                <el-select v-model="item.fieldValue" placeholder="请选择"  clearable v-selectClose style="width:260px" multiple collapse-tags>
                                    <el-option :label="lis" :value="lis" v-for="(lis,key) in item.optionContent" :key="key"/>
                                </el-select>  
                            </div>
                        </div>
 
                    </div>
                </el-form>
            </div>
            <div class="info-lis" v-show="moduleType == '批发信息'">
                <el-form :model="batchForm" label-width="120px" ref="batchFormRef" :rules="batchRules">
                    <div class="lis-item">
                        <div class="lis-i" style="width:100%">
                            <el-form-item label="批发状态" prop="wholesaleInfoState" :rules="getRules('select', '批发状态')">
                                <el-radio-group v-model="batchForm.wholesaleInfoState" class="ml-4" @change="changeWholesaleInfoState">
                                    <el-radio :label="1">正常</el-radio>
                                    <el-radio :label="2">停发</el-radio>
                                </el-radio-group>
                                <div style="font-size:12px;color:#666666;line-height:12px;width:100%;margin-top:3px">
                                    正常时，集团总部可向各个门店批发产品/物资
                                </div>
                            </el-form-item>
                        </div>

                    </div>
                    <div class="lis-item" v-if="batchForm.wholesaleInfoState == 1">
                        <div class="lis-i">
                            <el-form-item label="批发价" :rules="getRules('input', '批发价')" prop="wholesaleInfoPrice">
                                <el-input v-model="batchForm.wholesaleInfoPrice" placeholder="请输入" style="width:260px" @input="()=>{batchForm.wholesaleInfoPrice=limitFloat(batchForm.wholesaleInfoPrice)}" @blur="()=>{batchForm.wholesaleInfoPrice=giveFloatMin(batchForm.wholesaleInfoPrice)}"/>
                            </el-form-item>
                        </div>
  
                    </div>
                    <div class="lis-item" v-if="batchForm.wholesaleInfoState == 1">
                        <div class="lis-i">
                            <el-form-item label="批发分类" :rules="getRules('select', '批发价')" prop="wholesaleInfoClassification">
                                <el-select v-model="batchForm.wholesaleInfoClassification" placeholder="请选择"  clearable v-selectClose style="width:260px" multiple collapse-tags>
                                    <el-option :label="item.label" :value="item.value" v-for="(item,index) in batchClassifyList" :key="index"/>
                                </el-select>  
                            </el-form-item>
                        </div>
  
                    </div>
                    <div class="lis-item" v-if="batchForm.wholesaleInfoState == 1">
                        <div class="lis-i">
                            <el-form-item label="起购数量" :rules="getRules('input', '起购数量')" prop="wholesaleInfoMinimumPurchase">
                                <el-input v-model="batchForm.wholesaleInfoMinimumPurchase" placeholder="请输入" style="width:260px" clearable @input="()=>{batchForm.wholesaleInfoMinimumPurchase=limitInt(batchForm.wholesaleInfoMinimumPurchase)}" @blur="()=>{batchForm.wholesaleInfoMinimumPurchase=giveIntMin(batchForm.wholesaleInfoMinimumPurchase)}" :maxlength="10"/>
                            </el-form-item>
                        </div>
  
                    </div>
                    <div class="lis-item" v-if="batchForm.wholesaleInfoState == 1">
                        <div class="lis-i" style="width:100%">
                            <el-form-item label="物资详情" prop="wholesaleInfoDetails">
                                <el-input v-model="batchForm.wholesaleInfoDetails" placeholder="请输入" style="width:260px;" :rows="5" type="textarea" :maxlength="500"/>
                                <div style="width:100%;position: relative;margin-top: 10px;">
                                    <UploadImg :multiple="true" @backValue="backValueActivityDetailImg"  :imageListUrlInfo="batchForm.wholesalepictureList" :maxImgLength="20">
                                    </UploadImg>
                                    <div style="font-size:12px;color:#666666;line-height:12px;width:100%;margin-top:8px">
                                        支持jpg、jpeg、png格式最多20张，单张不超过5M
                                    </div>
                                </div>
                            </el-form-item>
                        </div>

                    </div>
                </el-form>
            </div>
        </div>

    </div>
</template>
<style lang="less" scoped>
.normal-table{
    :deep(.el-table){
        border:1px solid #E3E3E3;
    }
    :deep(.el-table--enable-row-transition){
        .el-table__body td.el-table__cell{
            background: #fff; 
        }
    }
}
:deep(.el-table__inner-wrapper::before){
    display:none;
}
:deep(.el-table th.el-table__cell){
    background: #EBEBEB;
}
:deep(.el-dialog__body){
    padding:0 4px;
}
:deep(.el-table__header){
    tr{
        th{
            &:last-child{
                .cell{
                    border-right: 0px;
                }
            }
        }
    }
}
.page-contain{
    width: 100%;
    height: 100%;
    :deep(.el-table th > .cell){
        border-right: 0;;
    }
    :deep(.el-radio-button:first-child .el-radio-button__inner){
        border-left:1px solid #3480FF;
    }
    .info-contain{
        width: 100%;
        height: calc(100% - 48px);
        box-sizing: border-box;
        padding:16px 24px;
        .btn-opea{
            width: 100%;
            height: 32px;
        }
        .info-lis{
            width: 100%;
            height: calc(100% - 32px);
            box-sizing:border-box;
            padding-top:24px;
            overflow:auto;
            .lis-head{
                    width: 100%;
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;
                    padding-bottom:16px;
                    .icon-view{
                        margin-right: 8px;
                        position: relative;
                        width: 14px;
                        height: 14px;

                        &::before {
                            content: "";
                            position: absolute;
                            top: 0;
                            left: 0;
                            width: 10px;
                            height: 10px;
                            border-radius: 2px;
                            background-color: #10E7F9; 
                        }
                        .icon-view-on{
                            position: absolute;
                            bottom: 0;
                            right: 0;
                            width: 10px;
                            height: 10px;
                            border-radius: 2px;
                            background-color: #3480FF; /* 背景色 */
                        }
                    }
                    .label-name{
                        color: #000000;
                        font-weight: bold;
                        font-size: 14px;
                        margin-right: 8px;
                    }
                    img{
                        width: 14px;
                        height: 14px;
                        cursor: pointer;
                    }
                }
        }
        .lis-item{
            width: 100%;
            display: flex;
            justify-content: flex-start;
            flex-wrap: wrap;
            .lis-i{
                width: calc(100% / 3);
                margin-bottom:10px;
            }
            .lis-i-other{
                display: flex;
                justify-content: flex-start;
                align-items: center;
                .l-name{
                    width: 80px;
                    text-align: right;
                    word-break: break-all;
                    word-wrap: break-word;
                    display: flex;
                    justify-content: flex-end;
                    align-items: center;
                    min-height: 32px;
                    padding: 0 12px 0 0;
                    font-size: var(--el-form-label-font-size);
                    color: var(--el-text-color-regular);
                    line-height: 20px;
                }
                
            }
        }
    }
    :deep(.el-table__row){
        .el-input .el-input__wrapper{
            background: rgba(0,0,0,0);
        }
    }
}
.input-line{
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom:16px;
    &:last-child{
        margin-bottom:0px;
    }
    img{
        cursor: pointer;
        width: 16px;
        height: 16px;
        margin-left:8px;
    }
}

</style>